import datetime
import os
import time
import traceback


import requests
from loguru import logger
from playwright.sync_api import sync_playwright


class Wanda:
    def __init__(self, playwright):
        self.playwright = playwright
        self.context = None
        self.browser = None
        self.page = None
        self.index_url = "https://www.mabangerp.com/index.htm"
        self.user_name = "13724266625"
        self.pwd = "test123456"

    def run(self):
        browser = self.playwright.chromium.launch(headless=False)
        self.context = browser.new_context(accept_downloads=True)
        self.page = self.context.new_page()
        self.page.goto(self.index_url, timeout=60000)
        self.wait(self.page)
        # 点击登录按钮
        self.page.click('//*[@id="login-btn"]')
        time.sleep(0.5)
        # 输入账号
        self.page.fill('//*[@id="account"]', self.user_name)
        # 输入密码
        self.page.fill('//*[@id="password"]', self.pwd)
        # 点击登录
        self.page.click('//*[@id="account-btn"]')
        self.wait(self.page)
        # 导航到订单列表
        self.page.goto('https://www.mabangerp.com/index.php?mod=order.list&Order_orderStatus=2')
        self.wait(self.page)
        # 点击全部订单
        self.page.click('//*[@id="processingOrderUl"]/li[10]/a/span')
        self.wait(self.page)
        # 点击高级搜索
        self.page.query_selector('//*[@id="searchSubmit"]').query_selector('//*[@id="AdvanceSearchBtn"]').click()
        self.wait(self.page)
        # 点击状态
        self.page.select_option('//*[@id="statusCh"]', label="全部状态")
        # 点击查询时间段
        self.page.select_option('//*[@id="query-time"]', label="付款时间")
        # 开始时间
        # 格式化当前时间
        start_time = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d") + " 16:00:00"
        end_time = datetime.datetime.now().strftime("%Y-%m-%d") + " 16:00:00"
        logger.info("开始时间：" + start_time)
        logger.info("结束时间：" + end_time)
        # 设置开始时间
        self.page.fill('//*[@id="datepicker-from2"]', start_time)
        self.page.keyboard.press("Enter")
        self.page.keyboard.press("Tab")
        # 设置结束时间
        self.page.keyboard.type(end_time)
        self.page.keyboard.press("Enter")
        # 点击标题
        self.page.click('//*[@id="searchDetail"]/div[1]/h4')
        self.page.keyboard.press("End")
        # 点击搜索
        self.page.click('//*[@id="searchMore"]')
        self.wait(self.page)
        # 检查是否查询到记录
        if self.page.query_selector('//*[@id="vue-list-body"]/li/div/p') and "没有找到相关记录" in self.page.query_selector(
                '//*[@id="vue-list-body"]/li/div/p').text_content():
            logger.info("没有找到相关记录")
            return
        time.sleep(1)
        # 关闭设置
        self.page.click('//*[@id="pageSettings"]/div[1]/h3/a/i')
        # 点击导出选项
        self.page.click('//*[@id="upLoadMenu"]/button/span[1]')
        # 点击订单导出
        self.wait(self.page)
        with self.page.expect_popup() as popup_info:
            self.page.click('//*[@id="upLoadMenu"]/ul/li[3]/a')
        new_page = popup_info.value
        self.wait(new_page)
        # 等待页面加载完整
        new_page.wait_for_load_state()
        # 循环30次
        page_completed = False
        for i in range(30):
            if len(new_page.frames) > 0 and new_page.frame('iframeContent'):
                # 如果iframeContent存在，则跳出循环
                page_completed = True
                # 等待页面加载完成
                time.sleep(5)
                break
            else:
                logger.info("iframeContent不存在，继续等待")
                time.sleep(1)
        if not page_completed:
            logger.info("iframeContent不存在，退出")
            return
        # 加载导出模板
        self.wait(new_page)
        new_page.frame('iframeContent').click('//*[@id="exportsaveasd"]/div/button/span[1]')
        time.sleep(1)
        # 选择RPA专用模板
        new_page.frame('iframeContent').click('//*[@id="exportsaveasd"]/div/ul/li[2]/a')
        self.wait(new_page)
        time.sleep(2)
        # 往下滑动
        new_page.keyboard.press("End")
        time.sleep(1)
        # 导出
        with new_page.expect_download() as download_info:
            new_page.frame('iframeContent').click('//*[@id="exportsaveas"]/button[2]')
        download_obj = download_info.value
        file_dir = os.path.join(os.getcwd(), "temp")
        if not os.path.exists(file_dir):
            os.mkdir(file_dir)
        file_path = os.path.join(file_dir, download_obj.suggested_filename)
        download_obj.save_as(file_path)
        # 等待文件下载完成
        for i in range(60):
            if os.path.exists(file_path):
                break
            time.sleep(1)
        # 上传文件到服务器
        self.upload_file(file_path)
        # 删除临时文件
        os.remove(file_path)

    def upload_file(self, file_path):
        logger.info("正在上传文件：" + file_path)
        url = "http://192.168.3.49:8990/api/v1/mbOrder/sysMbOrderRPADailyImport"
        # url = "http://1.95.166.150:8996/api/v1/mbOrder/sysMbOrderRPADailyImport"
        logger.info("正在上传文件到服务器：" + url)
        files = [
            ('file', (open(file_path, 'rb')))
        ]
        res = requests.request("POST", url, files=files)
        logger.info(res.text)

    def wait(self, page, seconds=1):
        page.wait_for_load_state(state="domcontentloaded")
        time.sleep(seconds)

    def close(self):
        try:
            if self.page:
                self.page.close()
        except:
            pass
        try:
            if self.browser:
                self.browser.close()
        except:
            pass
        try:
            if self.context:
                self.context.close()
        except:
            pass

def post_success():
    url = "http://192.168.3.49:8990/api/v1/mission/finish/RPA-JOB"
    res = requests.request("GET", url)
    logger.info(res.text)


def post_error(error_text):
    url = "http://192.168.3.49:8990/api/v1/mission/error/RPA-JOB"
    logger.info(error_text)
    res = requests.request("POST", url, json={"remark": error_text})
    logger.info(res.text)

if __name__ == '__main__':
    # 记录日期的路经
    logger.add(os.path.join(os.getcwd(), 'logs', f'{datetime.datetime.now().strftime("%Y-%m-%d")}-mbOrder.txt'))
    for i in range(3):
        try:
            with sync_playwright() as playwright:
                wanda = Wanda(playwright)
                wanda.run()
                wanda.close()
                break
        except:
            logger.info(traceback.format_exc())
